<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 5/24/21
 * Time: 9:15 PM
 */

namespace app\api\controller\v1;

use app\api\model\Product as ProductModel;
use app\api\model\ProductCoupon;
use LinCmsTp5\exception\ParameterException;
use think\Db;

// 产品
class Product
{
    /**
     * 获取产品列表
     * @validate('PagingParameter')
     */
    public function getDataList($name,$store_id,$page,$limit,$up_down)
    {
        $where[] = ['up_down','eq',$up_down];
        $where[] = ['product_type','eq',1];
        if($name) {
            $where[] = ['name','like','%'.$name.'%'];
        }
        if($store_id) {
            $where[] = ['store_id','eq',$store_id];
        }
        $query = ProductModel::where($where)->with('img,coupon,store')->order('order_sort desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取专属卡产品全部
     */
    public function getTypeDataAll()
    {
        $where[] = ['product_type','eq',2];
        return ProductModel::where($where)->with('img')->order('id desc')->select()->toArray();
    }

    /**
     * 获取专属卡产品列表
     * @validate('PagingParameter')
     */
    public function getTypeDataList($name,$page,$limit)
    {
        $where[] = ['product_type','eq',2];
        if($name) {
            $where[] = ['name','like','%'.$name.'%'];
        }
        $query = ProductModel::where($where)->with('store,img')->order('id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取产品详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return ProductModel::where('id',$id)->with('img,coupon')->find();
    }

    /**
     * 添加产品
     * @validate('CheckProduct')
     */
    public function createData($name,$img_id,$sales_volume,$original_price,$present_price,$new_user_price,
                               $desc,$invite_cash,$invite_cash_two,$group_invite_cash,$new_user_invite_cash,
                               $boss_cash,$start_time,$end_time,$order_sort,$max_num,$coupon_status,$coupon,$store_id)
    {
        Db::startTrans();
        try{
            $mode = ProductModel::create([
                'name' => $name,
                'img_id' => $img_id,
                'sales_volume' => $sales_volume,
                'order_sort' => $order_sort,
                'max_num' => $max_num,
                'original_price' => $original_price,
                'present_price' => $present_price,
                'new_user_price' => $new_user_price,
                'invite_cash' => $invite_cash,
                'invite_cash_two' => $invite_cash_two,
                'group_invite_cash' => $group_invite_cash,
                'new_user_invite_cash' => $new_user_invite_cash,
                'boss_cash' => $boss_cash,
                'start_time' => strtotime($start_time),
                'end_time' => strtotime($end_time),
                'desc' => $desc,
                'coupon_status' => $coupon_status,
                'store_id' => $store_id
            ]);
            if($coupon_status === '1') {
                $this->checkCoupon($coupon);
                ProductCoupon::create([
                    'product_id' => $mode->id,
                    'name' => $coupon['name'],
                    'amount_of_money' => $coupon['amount_of_money'],
                    'amount_of_money_use' => $coupon['amount_of_money_use'],
                    'money' => $coupon['money'],
                    'usage_times' => $coupon['usage_times'],
                    'start_time' => strtotime($coupon['start_time']),
                    'end_time' => strtotime($coupon['end_time'])
                ]);
            }
            Db::commit();
            return writeJson(201, [], '添加成功！');
        } catch (\Exception $e){
            Db::rollback();
            throw new ParameterException([
                'msg' => [
                    'product' => '添加失败!'
                ]
            ]);
        }
    }

    /**
     * 添加产品
     * @validate('CheckProductType')
     */
    public function createTypeData($name,$img_id,$store_id,$present_price,
                                   $desc,$group_invite_cash,$new_user_pay_cash,
                                   $end_time)
    {
        ProductModel::create([
            'name' => $name,
            'img_id' => $img_id,
            'store_id' => $store_id,
            'present_price' => $present_price,
            'group_invite_cash' => $group_invite_cash,
            'new_user_pay_cash' => $new_user_pay_cash,
            'end_time' => $end_time,
            'product_type' => 2,
            'desc' => $desc
        ]);
        return writeJson(201, [], '添加成功！');
    }

    /**
     * 上下架操作
     */
    public function setUpDown($product_ids,$up_down)
    {
        $product = ProductModel::where('id','in',$product_ids)->select();
        if($product->isEmpty()) {
            throw new ParameterException([
                'msg' => [
                    'product' => '请选择产品'
                ]
            ]);
        }
        ProductModel::where('id','in',$product_ids)->update([
            'up_down' => $up_down
        ]);
        return writeJson(201, [], '操作成功！');
    }


    /**
     * 添加产品
     * @validate('CheckProductType')
     */
    public function updateTypeData($id,$name,$img_id,$store_id,$present_price,
                                   $desc,$group_invite_cash,$new_user_pay_cash,
                                   $end_time)
    {
        $info = ProductModel::get($id);
        if ($info) {
            $info->name = $name;
            $info->store_id = $store_id;
            $info->img_id = $img_id;
            $info->present_price = $present_price;
            $info->group_invite_cash = $group_invite_cash;
            $info->new_user_pay_cash = $new_user_pay_cash;
            $info->end_time = $end_time;
            $info->desc = $desc;
            $info->save();
        }
        return writeJson(202, [], '修改成功！');
    }

    /**
     * 修改产品
     * @validate('CheckProduct')
     */
    public function updateData($id,$name,$sales_volume,$img_id,$original_price,$present_price,$new_user_price,
                               $desc,$invite_cash,$invite_cash_two,$group_invite_cash,$new_user_invite_cash,
                               $start_time,$end_time,$order_sort,$max_num,$coupon_status,$coupon,$store_id)
    {
        Db::startTrans();
        try {
            $info = ProductModel::get($id);
            if ($info) {
                $info->name = $name;
                $info->img_id = $img_id;
                $info->order_sort = $order_sort;
                $info->max_num = $max_num;
                $info->sales_volume = $sales_volume;
                $info->original_price = $original_price;
                $info->present_price = $present_price;
                $info->new_user_price = $new_user_price;
                $info->invite_cash = $invite_cash;
                $info->invite_cash_two = $invite_cash_two;
                $info->group_invite_cash = $group_invite_cash;
                $info->new_user_invite_cash = $new_user_invite_cash;
                $info->start_time = strtotime($start_time);
                $info->end_time = strtotime($end_time);
                $info->desc = $desc;
                $info->coupon_status = $coupon_status;
                $info->store_id = $store_id;
                $info->save();
                if ($coupon_status === '1') {
                    $this->checkCoupon($coupon);
                    $coupon_info = ProductCoupon::where('product_id', 'eq', $id)->find();
                    if ($coupon_info) {
                        $coupon_info->name = $coupon['name'];
                        $coupon_info->amount_of_money = $coupon['amount_of_money'];
                        $coupon_info->amount_of_money_use = $coupon['amount_of_money_use'];
                        $coupon_info->money = $coupon['money'];
                        $coupon_info->usage_times = $coupon['usage_times'];
                        $coupon_info->start_time = strtotime($coupon['start_time']);
                        $coupon_info->end_time = strtotime($coupon['end_time']);
                        $coupon_info->save();
                    } else {
                        ProductCoupon::create([
                            'product_id' => $id,
                            'name' => $coupon['name'],
                            'amount_of_money' => $coupon['amount_of_money'],
                            'amount_of_money_use' => $coupon['amount_of_money_use'],
                            'money' => $coupon['money'],
                            'usage_times' => $coupon['usage_times'],
                            'start_time' => strtotime($coupon['start_time']),
                            'end_time' => strtotime($coupon['end_time'])
                        ]);
                    }
                }
            }
            Db::commit();
            return writeJson(202, [], '修改成功！');
        }catch (\Exception $e){
            throw new ParameterException([
                'msg' => [
                    'product' => '修改失败!'
                ]
            ]);
        }
    }

    /**
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        ProductModel::destroy($id);
        ProductCoupon::destroy(['product_id'=>$id]);
        return writeJson(203, [], '删除成功！');
    }


    private function checkCoupon($coupon){
        if(!$coupon['name']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券名称'
                ]
            ]);
        }
        if(!$coupon['amount_of_money']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券满额-得到'
                ]
            ]);
        }
        if(!$coupon['amount_of_money_use']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券满额-使用'
                ]
            ]);
        }
        if(!$coupon['money']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券金额'
                ]
            ]);
        }
        if(!$coupon['usage_times']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券使用次数'
                ]
            ]);
        }
        if(!$coupon['start_time']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券开始使用时间'
                ]
            ]);
        }
        if(!$coupon['end_time']) {
            throw new ParameterException([
                'msg' => [
                    'product_coupon' => '请输入优惠券结束使用时间'
                ]
            ]);
        }
    }
}